package org.ws.httphelper.support.pipeline.handler.response;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.MapUtils;
import org.ws.httphelper.core.pipeline.HandlerOrder;
import org.ws.httphelper.core.pipeline.ResponseHandler;
import org.ws.httphelper.exception.ParseException;
import org.ws.httphelper.exception.ResponseException;
import org.ws.httphelper.model.RequestContext;
import org.ws.httphelper.model.config.RequestConfig;
import org.ws.httphelper.model.field.ParseField;
import org.ws.httphelper.model.http.ResponseFuture;
import org.ws.httphelper.model.http.ResponseType;
import org.ws.httphelper.support.parser.HtmlObjectParser;

import java.util.Map;

@HandlerOrder(1)
public class ParseHtmlHandler implements ResponseHandler {

    private HtmlObjectParser htmlObjectParser = new HtmlObjectParser();

    @Override
    public boolean handler(RequestContext requestContext) throws ResponseException {
        ResponseFuture responseFuture = requestContext.getResponseFuture();
        if (responseFuture == null
                || responseFuture.getResponseType() != ResponseType.HTML) {
            return true;
        }
        Class outputClass = requestContext.getOutputClass();
        // 默认转化成map
        if(outputClass == null){
            outputClass = Map.class;
        }
        RequestConfig requestConfig = requestContext.getRequestConfig();
        Map<String, ParseField> parseFieldMap = requestConfig.getParseHtmlFields();
        if(MapUtils.isEmpty(parseFieldMap)){
            return true;
        }
        if(responseFuture.isSuccess()){
            try {
                String html = (String) responseFuture.getResponse().getBody();
                // 解析map
                Map<String, Object> map = htmlObjectParser.parse(html,parseFieldMap.values());
                if(outputClass != Map.class) {
                    // 转化成json
                    String json = JSON.toJSONString(map);
                    // 转化成object
                    Object output = JSON.parseObject(json, outputClass);
                    responseFuture.setOutput(output);
                }
                else {
                    responseFuture.setOutput(map);
                }
            } catch (ParseException e) {
                throw new ResponseException(e.getMessage(),e);
            }
        }
        return true;
    }

}
